package huxibianjie.com.lbscandroid.ui.new_activity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import huxibianjie.com.lbscandroid.Constants;
import huxibianjie.com.lbscandroid.R;
import huxibianjie.com.lbscandroid.base.BaseActivity;
import huxibianjie.com.lbscandroid.event.ClickEvent;
import huxibianjie.com.lbscandroid.event.LoginEvent;
import huxibianjie.com.lbscandroid.manager.RouteManager;
import huxibianjie.com.lbscandroid.manager.UserManager;
import huxibianjie.com.lbscandroid.model.UserModel;
import huxibianjie.com.lbscandroid.model.VersionModel;
import huxibianjie.com.lbscandroid.pedomemter.StepDetector;
import huxibianjie.com.lbscandroid.pedomemter.StepService;
import huxibianjie.com.lbscandroid.task.Callback;
import huxibianjie.com.lbscandroid.task.Task;
import huxibianjie.com.lbscandroid.ui.Service;
import huxibianjie.com.lbscandroid.util.AppManager;
import huxibianjie.com.lbscandroid.util.MyLog;
import huxibianjie.com.lbscandroid.util.PrefsUtils;
import huxibianjie.com.lbscandroid.util.SystemUtils;
import huxibianjie.com.lbscandroid.util.Utils;
import huxibianjie.com.lbscandroid.widget.CircleProgress;
import huxibianjie.com.lbscandroid.widget.NoDoubleClickUtils;
import huxibianjie.com.lbscandroid.widget.ScaleProgress;
import rx.functions.Action1;

/**
 * 主界面
 */
public class HomeActivity extends BaseActivity implements StepListener, View.OnClickListener, AMapLocationListener {
    private long intervalTime = 5 * 60 * 1000 + 10000;//间隔提交时间
    private long curStep;
    private long submitStepCache;//今日提交过的缓存步数
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            StepService.MyBinder binder = ((StepService.MyBinder) service);
            binder.addStepInterface(HomeActivity.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    private ScaleProgress scaleProgress;
    private CircleProgress circleProgress;
    private MapView mMapView = null;
    private AMap aMap;

    private TextView tvName, tvMoney, tvLoginBtn, tvStep, tvDoubleEnergy, tvCurrentStep, tvInfo;
    private LinearLayout layActivity, layPersonal;
    private RelativeLayout layInfo;
    private TextView tvExplain;


    //声明mlocationClient对象
    public AMapLocationClient mLocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMapView = findViewById(R.id.map);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        mMapView.onCreate(savedInstanceState);
        mMapView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ViewGroup child = (ViewGroup) mMapView.getChildAt(0);//地图框架
                child.getChildAt(2).setVisibility(View.GONE);//logo
                // child.getChildAt(5).setVisibility(View.VISIBLE);//缩放按钮
                // child.getChildAt(6).setVisibility(View.VISIBLE);//定位按钮
                // child.getChildAt(7).setVisibility(View.VISIBLE);//指南针
            }
        });
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.getUiSettings().setAllGesturesEnabled(false);
        bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_location));
        new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {

            }
        });

        new RxPermissions(this).request(Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {
                if (aBoolean) {
                    //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
                    mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                    //设置定位间隔,单位毫秒,默认为2000ms
                    mLocationOption.setInterval(2000);
                    //设置定位参数
                    mLocationClient.setLocationOption(mLocationOption);
                    // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
                    // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
                    // 在定位结束后，在合适的生命周期调用onDestroy()方法
                    // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
                    // 启动定位
                    mLocationClient.startLocation();
                } else {
                    showToast("拒绝了定位权限");
                }
            }
        });
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_home;
    }

    @Override
    protected void initView() {
        submitStepCache = PrefsUtils.read(this, Constants.LAST_STEP, 0L);
        scaleProgress = findViewById(R.id.scale_progress);
        circleProgress = findViewById(R.id.circle_progress);
        tvName = findViewById(R.id.tv_name);
        tvMoney = findViewById(R.id.tv_money);
        tvLoginBtn = findViewById(R.id.tv_login_btn);
        tvStep = findViewById(R.id.tv_step);
        tvDoubleEnergy = findViewById(R.id.tv_double_energy);
        tvCurrentStep = findViewById(R.id.tv_current_step);
        tvInfo = findViewById(R.id.tv_info);
        layActivity = findViewById(R.id.lay_activity);
        layPersonal = findViewById(R.id.lay_personal);
        layInfo = findViewById(R.id.lay_info);
        tvExplain = findViewById(R.id.tv_explain);


        Typeface typefaceHeat = Typeface.createFromAsset(getAssets(), "fonts/haettenschweiler.ttf");
        tvStep.setTypeface(typefaceHeat);


        mLocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mLocationClient.setLocationListener(this);

    }

    @Override
    protected void initData() {
        int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
        int screenHeight = getWindowManager().getDefaultDisplay().getHeight();

        if (screenWidth <= 768 && screenHeight <= 1280) {
            int x8 = (int) getResources().getDimension(R.dimen.x8);
            circleProgress.setPadding(x8, x8, x8, x8);
        } else {
            int x18 = (int) getResources().getDimension(R.dimen.x18);
            circleProgress.setPadding(x18, x18, x18, x18);
        }
        requestUserInfo();
        requestInvite();
    }

    private void loadData() {
        if (UserManager.getInstance().isLogin()) {
            UserModel userModel = UserManager.getInstance().getUserModel();
            tvName.setText(Utils.starPhone(userModel.getPhone()));
            tvMoney.setText(String.valueOf("我的LBSC：" + userModel.getMoney()));
            tvLoginBtn.setVisibility(View.GONE);
            int toDayStep = (int) (userModel.getTodayStep() * 0.01);
            if (toDayStep > 100) {
                toDayStep = 100;
            }
            circleProgress.setProgress(toDayStep);
            tvDoubleEnergy.setText(String.valueOf("双倍能量：" + userModel.getGoldPool()));

            requestSubmitTime();
        } else {
            tvName.setText("游客账号");
            tvMoney.setText(String.valueOf("我的LBSC：0"));
            tvDoubleEnergy.setText(String.valueOf("双倍能量：0"));
            tvLoginBtn.setVisibility(View.VISIBLE);
            circleProgress.setProgress(0);
            stepUpState();
        }
        checkUserInfo();
    }

    private void inviteDialog() {
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(HomeActivity.this);
        builder.setTitle("绑定邀请人");
        builder.setMessage("绑定邀请人，即刻获得1000双倍能量也可在活动任务中的邀请好友界面绑定");
        builder.setCancelable(false);
        builder.setPositiveButton("去绑定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                RouteManager.getInstance().showInviteFriendActivity(HomeActivity.this);
            }
        });
        builder.setNegativeButton("不再提示", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (UserManager.getInstance().isLogin()) {
                    PrefsUtils.write(HomeActivity.this,
                            String.valueOf(UserManager.getInstance().getUserModel().getId()), true);
                }
                dialog.dismiss();
            }
        });
        builder.show();
    }

    @Override
    public void onClickEvent(ClickEvent event) {
        super.onClickEvent(event);
        switch (event.type) {
            case NET_WORK_STATE:
                if ((boolean) event.data) {
                    requestUserInfo();
                }
                break;
            case REFRESH_USER_INFO_SUCCESS:
                loadData();
                break;
        }
    }

    private void requestInvite() {
        if (UserManager.getInstance().isLogin()) {
            final UserModel userModel = UserManager.getInstance().getUserModel();
            boolean isInviteNoLongerRemindDialog = PrefsUtils.read(this, String.valueOf(userModel.getId()), false);
            if (!isInviteNoLongerRemindDialog) {
                Task.create(Service.class).getHomeInvitationRecord(String.valueOf(userModel.getId())).enqueue(new Callback<String>() {
                    @Override
                    public void onSuccess(@Nullable String s) {
                        if (s == null) return;
                        if (s.equals("0")) {
                            inviteDialog();
                        } else {
                            PrefsUtils.write(HomeActivity.this,
                                    String.valueOf(userModel.getId()), true);
                        }
                    }

                    @Override
                    public void onFailure(@NonNull String error) {

                    }
                });
            }
        }
    }

    private void requestUserInfo() {
        if (UserManager.getInstance().isLogin()) {
            String phone = UserManager.getInstance().getUserModel().getPhone();
            MyLog.e("ambit", phone);
            if (phone != null && !phone.equals("")) {
                showLoading();
                Task.create(Service.class).getUserInfo(phone).enqueue(new Callback<UserModel>() {
                    @Override
                    public void onSuccess(@Nullable UserModel userModel) {
                        if (userModel != null) {
                            UserManager.getInstance().save(userModel, false);
                            loadData();
                        }
                        cancelLoading();
                    }

                    @Override
                    public void onFailure(@NonNull String error) {
//                        showToast(error);
                        loadData();
                        cancelLoading();
                    }
                });
            }
        } else {
            loadData();
        }

    }

    @Override
    public void onLoginEvent(LoginEvent event) {
        super.onLoginEvent(event);
        requestInvite();
        loadData();
    }

    /**
     * 是大于5分钟
     */
    private boolean isGt5m = false;

    private void stepUpState() {
        if (UserManager.getInstance().isLogin()) {
            UserModel userModel = UserManager.getInstance().getUserModel();
            if (userModel.getTodayStep() >= 10000) {
                tvCurrentStep.setBackgroundResource(R.drawable.ic_home_battery_limit);
                tvCurrentStep.setEnabled(false);
                tvCurrentStep.setText("");
                tvInfo.setText("多多走路，健康币又多");
                return;
            }
        }
        tvCurrentStep.setBackgroundResource(R.drawable.bg_home_battery);
        boolean isSubmit;
        if (UserManager.getInstance().isLogin()) {
            isSubmit = curStep >= 50 && isGt5m;
        } else {
            isSubmit = curStep >= 50;
        }
        tvCurrentStep.setEnabled(isSubmit);
        if (isSubmit) {
            double lbsc = (curStep / 2.0);
            if (lbsc > 500.0) {
                lbsc = 500;
            }
            tvCurrentStep.setText(String.valueOf("提转LBSC:" + lbsc));
            tvInfo.setText("注：次日清空，请及时点击上方提转");
        } else {
            tvCurrentStep.setText("");
            tvInfo.setText("多多走路，健康币又多");
        }
    }

    private long prevSubmitTime = 0;

    private void requestSubmitTime() {
        if (!UserManager.getInstance().isLogin()) return;
        String ids = String.valueOf(UserManager.getInstance().getUserModel().getId());
        Task.create(Service.class).getUserSubmitTime(ids).enqueue(new Callback<Long>() {
            @Override
            public void onSuccess(@Nullable Long aLong) {
                if (aLong != null) {
                    HomeActivity.this.prevSubmitTime = aLong;
                    long time = System.currentTimeMillis() - aLong;
                    isGt5m = aLong == 0 || time > intervalTime;
                    if (isGt5m) {
                        stopTimer();
                    } else {
                        startTimer(intervalTime - time);
                    }
                    stepUpState();
                }
            }

            @Override
            public void onFailure(@NonNull String error) {
                showToast(error);
            }
        });
    }

    private Timer timer;

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private void startTimer(long delay) {
        stopTimer();
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        isGt5m = true;
                        stepUpState();
                    }
                });

            }
        }, delay);
    }


    @Override
    protected void initListener() {
        tvDoubleEnergy.setOnClickListener(this);
        layActivity.setOnClickListener(this);
        layPersonal.setOnClickListener(this);
        tvCurrentStep.setOnClickListener(this);
        tvLoginBtn.setOnClickListener(this);
        layInfo.setOnClickListener(this);
        tvExplain.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mMapView.onDestroy();
        unbindService(conn);
    }

    private void startService() {
        Intent intent = new Intent(this, StepService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
        startService(intent);
    }

    private boolean isCheckVersion = true;

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
        startService();
        checkVersion();
        if (prevSubmitTime == 0) {
            requestSubmitTime();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    private void checkUserInfo() {
        UserModel userModel = UserManager.getInstance().getUserModel();
        if (userModel != null) {
            if (userModel.getSealUp() == 1) {
                android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(HomeActivity.this);
                builder.setTitle("账号异常通知：").
                        setMessage("账号:" + userModel.getPhone() + " 存在刷币行为，已被封禁！")
                        .setCancelable(false).setPositiveButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AppManager.getAppManager().finishActivity();
                    }
                });
                builder.show();
            }
        }
    }

    @Override
    public void onStepListener(long sumStep) {
        if (Constants.IS_CACHE_STEP) {
            submitStepCache = sumStep;
            long cacheValue = PrefsUtils.read(this, Constants.LAST_STEP, 0L);
            if ((submitStepCache - cacheValue) > 1000) {
                submitStepCache = cacheValue + 1000;
                PrefsUtils.write(this, Constants.LAST_STEP, submitStepCache);
            } else {
                PrefsUtils.write(this, Constants.LAST_STEP, submitStepCache);
            }
            Constants.IS_CACHE_STEP = false;
        }
        curStep = sumStep - submitStepCache;
        if (curStep < 0) {
            submitStepCache = 0;
            curStep = 0;
        }
        scaleProgress.setProgress(sumStep < 100 && sumStep > 0 ? 1 : (int) (sumStep * 0.01));
        tvStep.setText(String.valueOf(sumStep > 10000 ? 10000 : sumStep));

        if (submitStepCache >= 10000 && UserManager.getInstance().isLogin() && UserManager.getInstance().getUserModel().getTodayStep() < 10000) {
            tvCurrentStep.setBackgroundResource(R.drawable.ic_home_battery_online);
            tvCurrentStep.setEnabled(false);
            tvCurrentStep.setText("");
            tvInfo.setText("多多走路，健康币又多");
            return;
        }
        stepUpState();
    }

    /**
     * 真实提币（步数）
     */
    private long toTurnStep;

    @Override
    public void onClick(View view) {
        if (NoDoubleClickUtils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_explain:
                RouteManager.getInstance().showExplainActivity(this);
                break;
            case R.id.lay_info:
                if (!UserManager.getInstance().isLogin()) {
                    RouteManager.getInstance().showLoginActivity(this);
                    return;
                }
                RouteManager.getInstance().showMyPageActivity(this);
                break;
            case R.id.tv_double_energy:
                RouteManager.getInstance().showEnergyRuleActivity(this);
                break;
            case R.id.tv_login_btn:
                RouteManager.getInstance().showLoginActivity(this);
                break;
            case R.id.tv_current_step:
                if (!UserManager.getInstance().isLogin()) {
                    RouteManager.getInstance().showLoginActivity(this);
                    return;
                }
                toTurnStep = curStep;
                if (toTurnStep < Constants.number) {
                    showToast("50步以后可提交，上限为1000步~");
                    return;
                }
                if (toTurnStep > 1000) {
                    toTurnStep = 1000;
                }
                showLoading();
                String ids = String.valueOf(UserManager.getInstance().getUserModel().getId());
                Task.create(Service.class).submitStep(ids, toTurnStep).enqueue(new Callback<Map<String, String>>() {
                    @Override
                    public void onSuccess(@Nullable Map<String, String> mapData) {
                        if (mapData != null) {
                            showToast("当前位置信息打包成功");
                            UserModel userModel = UserManager.getInstance().getUserModel();
                            userModel.setTodayCurrency(mapData.containsKey("todayCurrency") ? Double.parseDouble(mapData.get("todayCurrency"))
                                    : userModel.getTodayCurrency());
                            userModel.setTaskCurrency(mapData.containsKey("taskCurrency") ? Double.parseDouble(mapData.get("taskCurrency"))
                                    : userModel.getTaskCurrency());
                            userModel.setMoney(mapData.containsKey("money") ? Double.parseDouble(mapData.get("money"))
                                    : userModel.getMoney());
                            userModel.setTotalAassets(mapData.containsKey("totalAassets") ? Double.parseDouble(mapData.get("totalAassets"))
                                    : userModel.getTotalAassets());
                            userModel.setGoldPool(mapData.containsKey("goldPool") ? Double.parseDouble(mapData.get("goldPool"))
                                    : userModel.getGoldPool());
                            userModel.setTodayStep(mapData.containsKey("todayStep") ? (int) Double.parseDouble(mapData.get("todayStep"))
                                    : userModel.getTodayStep());

                            UserManager.getInstance().save(userModel, false);

                            loadData();

                            HashMap<String, String> map = new HashMap<>();
                            map.put("phone", UserManager.getInstance().getUserModel().getPhone());
                            map.put("stepnumber", String.valueOf(toTurnStep));
                            MobclickAgent.onEvent(HomeActivity.this, "Withdrawmoney", map);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Constants.IS_CACHE_STEP = true;
                                    onStepListener(StepDetector.CURRENT_STEP);
                                }
                            }, 500);

                        } else {
                            showToast("提步失败");
                        }
                        cancelLoading();
                    }

                    @Override
                    public void onFailure(@NonNull String error) {
                        if (error != null && error.equals("签名失败")) {
                            isCheckVersion = true;
                            checkVersion();
                            return;
                        }
                        showToast(error);
                        cancelLoading();
                    }
                });
                break;
            case R.id.lay_activity://跳转活动界面
                if (!UserManager.getInstance().isLogin()) {
                    RouteManager.getInstance().showLoginActivity(this);
                    return;
                }
                RouteManager.getInstance().showCampaignActivity(this);
                break;
            case R.id.lay_personal://跳转我的界面
                if (!UserManager.getInstance().isLogin()) {
                    RouteManager.getInstance().showLoginActivity(this);
                    return;
                }
                RouteManager.getInstance().showMyPageActivity(this);
                break;
        }
    }

    private long exitTime = 0;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                showToast("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }


    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
        super.onBackPressed();
    }

    private void checkVersion() {
        if (!isCheckVersion) return;
        Task.create(Service.class).getVersionInfo("android").enqueue(new Callback<VersionModel>() {
            @Override
            public void onSuccess(@Nullable final VersionModel versionModel) {
                if (versionModel != null && versionModel.getVersionCode() > SystemUtils.getVersionCode(HomeActivity.this)) {
                    android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(HomeActivity.this);
                    builder.setTitle("发现新版本：" + versionModel.getVersionName());
                    builder.setMessage(versionModel.getContent());
                    builder.setCancelable(!versionModel.isMust());
                    builder.setPositiveButton("去下载更新", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
//                            File file = new File(Constants.APP_DOWN_PATH + Constants.APP_APK_NAME);
//                            if (file.exists()) {
//                                PackageInfo packageInfo =
//                                        getPackageManager().
//                                                getPackageArchiveInfo(Constants.APP_DOWN_PATH +
//                                                        Constants.APP_APK_NAME, PackageManager.GET_ACTIVITIES);
//                                if (packageInfo != null && getPackageName().equals(packageInfo.packageName)
//                                        && packageInfo.versionCode > SystemUtils.getVersionCode(HomeActivity.this)) {
//                                    installApk(file);
//                                    return;
//                                }
//                            }
//                            downLoadApk(versionModel.getApkUrl());
                            dialog.dismiss();
                            SystemUtils.openBrowser(HomeActivity.this, versionModel.getApkUrl());
                            if (versionModel.isMust()) {
                                AppManager.getAppManager().AppExit(HomeActivity.this);
                            }
                        }
                    });
                    builder.setNegativeButton(versionModel.isMust() ? "退出" : "取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            if (versionModel.isMust()) {
                                AppManager.getAppManager().AppExit(HomeActivity.this);
                            } else {
                                isCheckVersion = false;
                            }
                        }
                    });
                    builder.show();
                }
            }

            @Override
            public void onFailure(@NonNull String error) {

            }
        });
    }

    private BitmapDescriptor bitmapDescriptor;

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        // 设置当前地图显示为当前位置
        if (aMapLocation.getErrorCode() == 0) {
            if (aMap.getMapScreenMarkers().size() > 0)
                aMap.getMapScreenMarkers().get(0).remove();
            aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(aMapLocation.getLatitude(),
                    aMapLocation.getLongitude()), 19, 0, 0)));
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()));
            markerOptions.title("当前位置");
            markerOptions.visible(true);
            if (bitmapDescriptor != null)
                markerOptions.icon(bitmapDescriptor);
            aMap.addMarker(markerOptions);
        } else {
//            showToast(aMapLocation.getErrorInfo());
//            mLocationClient.stopLocation();
        }
    }
}
